using System;
using System.Linq;
using System.ServiceProcess;
using TripleA.Core.Interfaces.Exceptions;

namespace TripleA.Core.Extensions.WindowsService
{
    /// <summary>
    /// This asserts that a windows service is installed
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class WindowsServiceInstalledStep<T> : WindowsServiceStepBase<T>
    {
        protected virtual void Inspect(ServiceController serviceController)
        {
            // do nothing here, gives us an extension point when sub classed
            // to inspect the service and add new behaviour based on its state
        }

        public override void Execute(T context)
        {
            var sc = ServiceController.GetServices(Machine).FirstOrDefault(
                svc => svc.DisplayName.StartsWith(ServiceName,StringComparison.OrdinalIgnoreCase));

            if (sc == null)
                throw new ExpectationException("Service '{0}' is not installed on '{1}'", ServiceName, Machine);

            Inspect(sc);
        }
    }
}